package daily;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 2024-02-24
 * @Author Jonathan
 */
public class PrintABC2 {
    private static volatile Integer COUNT = 0;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread t1 = new Thread(() -> {
            // 代表一直打印
            for (; ; ) {
                lock.lock();
                while (COUNT % 3 != 0) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {

                    }
                }

                System.out.print("A");

                try {
                    TimeUnit.MICROSECONDS.sleep(1);
                } catch (InterruptedException e) {

                }
                COUNT++;
                condition.signalAll();
                lock.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            // 代表一直打印
            for (; ; ) {
                lock.lock();
                while (COUNT % 3 != 1) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {

                    }
                }

                System.out.print("B");

                try {
                    TimeUnit.MICROSECONDS.sleep(1);
                } catch (InterruptedException e) {

                }
                COUNT++;
                condition.signalAll();
                lock.unlock();
            }
        });

        Thread t3 = new Thread(() -> {
            // 代表一直打印
            for (; ; ) {
                lock.lock();
                while (COUNT % 3 != 2) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {

                    }
                }

                System.out.print("C");

                try {
                    TimeUnit.MICROSECONDS.sleep(1);
                } catch (InterruptedException e) {

                }
                COUNT++;
                condition.signalAll();
                lock.unlock();
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}
